package com.wujing.demo;

import java.util.Date;
import java.util.concurrent.*;

/**
 * @description: 异步线程调用
 * @author: wujing
 * @date: 2021/3/31 20:19
 */
public class AscyTaskDemo {
    static ExecutorService threadPool = Executors.newFixedThreadPool(2);

    public static void main(String[] args) {

        String s = doTask();
        System.out.println(s);
    }

    private static String doTask() {
        System.out.println("主线程任务开始");
        CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("耗时10s钟--->主任务结束");
            return "true";
        }, threadPool);
        task1.thenRunAsync(() -> {
            while (true) {
                System.out.println("时间：" + new Date() + "--->此任务");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, threadPool);

        try {
            if ("true".equals(task1.get())) {
                System.out.println("主线程任务结束");
                return "true";
            }
            task1.isDone();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        return "false";
    }
}
